/*
 * Copyright 2019-present Open Networking Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.onosproject.k8snetworking.impl;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import io.fabric8.kubernetes.api.model.Service;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.event.ListenerRegistry;
import org.onosproject.k8snetworking.api.K8sServiceAdminService;
import org.onosproject.k8snetworking.api.K8sServiceEvent;
import org.onosproject.k8snetworking.api.K8sServiceListener;
import org.onosproject.k8snetworking.api.K8sServiceService;
import org.onosproject.k8snetworking.api.K8sServiceStore;
import org.onosproject.k8snetworking.api.K8sServiceStoreDelegate;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;

import java.util.Set;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
import static org.slf4j.LoggerFactory.getLogger;

/**
 * Provides implementation of administering and interfacing kubernetes service.
 */
@Component(
        immediate = true,
        service = {K8sServiceAdminService.class, K8sServiceService.class}
)
public class K8sServiceManager
        extends ListenerRegistry<K8sServiceEvent, K8sServiceListener>
        implements K8sServiceAdminService, K8sServiceService {

    protected final Logger log = getLogger(getClass());

    private static final String MSG_SERVICE  = "Kubernetes service %s %s";
    private static final String MSG_CREATED = "created";
    private static final String MSG_UPDATED = "updated";
    private static final String MSG_REMOVED = "removed";

    private static final String ERR_NULL_SERVICE  = "Kubernetes service cannot be null";
    private static final String ERR_NULL_SERVICE_UID  = "Kubernetes service UID cannot be null";

    private static final String ERR_IN_USE = " still in use";

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected CoreService coreService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected K8sServiceStore k8sServiceStore;

    private final K8sServiceStoreDelegate
            delegate = new InternalServiceStorageDelegate();

    private ApplicationId appId;

    @Activate
    protected void activate() {
        appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);

        k8sServiceStore.setDelegate(delegate);
        log.info("Started");
    }

    @Deactivate
    protected void deactivate() {
        k8sServiceStore.unsetDelegate(delegate);
        log.info("Stopped");
    }

    @Override
    public void createService(Service service) {
        checkNotNull(service, ERR_NULL_SERVICE);
        checkArgument(!Strings.isNullOrEmpty(service.getMetadata().getUid()),
                ERR_NULL_SERVICE_UID);

        k8sServiceStore.createService(service);

        log.info(String.format(MSG_SERVICE, service.getMetadata().getName(), MSG_CREATED));
    }

    @Override
    public void updateService(Service service) {
        checkNotNull(service, ERR_NULL_SERVICE);
        checkArgument(!Strings.isNullOrEmpty(service.getMetadata().getUid()),
                ERR_NULL_SERVICE_UID);

        k8sServiceStore.updateService(service);

        log.info(String.format(MSG_SERVICE, service.getMetadata().getName(), MSG_UPDATED));
    }

    @Override
    public void removeService(String uid) {
        checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_SERVICE_UID);

        synchronized (this) {
            if (isServiceInUse(uid)) {
                final String error = String.format(MSG_SERVICE, uid, ERR_IN_USE);
                throw new IllegalStateException(error);
            }

            Service service = k8sServiceStore.removeService(uid);

            if (service != null) {
                log.info(String.format(MSG_SERVICE,
                        service.getMetadata().getName(), MSG_REMOVED));
            }
        }
    }

    @Override
    public void clear() {
        k8sServiceStore.clear();
    }

    @Override
    public Service service(String uid) {
        checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_SERVICE_UID);
        return k8sServiceStore.service(uid);
    }

    @Override
    public Set<Service> services() {
        return ImmutableSet.copyOf(k8sServiceStore.services());
    }

    private boolean isServiceInUse(String uid) {
        return false;
    }

    private class InternalServiceStorageDelegate implements K8sServiceStoreDelegate {

        @Override
        public void notify(K8sServiceEvent event) {
            if (event != null) {
                log.trace("send kubernetes service event {}", event);
                process(event);
            }
        }
    }
}
